﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DotNetStar.TheKing.Web.Admin.Controllers
{
    using Domain;
    using Models;
    using Services;
    using Microsoft.AspNetCore.Authorization;
    using SDDP;
    [Area("admin")]
    [Authorize(Roles =Infrastructure.RoleDefinition.ADMINISTRATOR)]
    public class UserController : Controller
    {
        private IStorage<User, long> _userStorage;
        public UserController(IStorage<User,long> userStorage)
        {
            _userStorage = userStorage;
        }
        public IActionResult Index(SearchUserModel model=null)
        {

            var query = _userStorage.Query();

            if (model != null)
            {
                if (!model.Email.IsNullOrWhiteSpace())
                {
                    query = query.Where(m => m.Email.Contains(model.Email));
                }
                if (!model.Mobile.IsNullOrWhiteSpace())
                {
                    query = query.Where(m => m.Mobile.Contains(model.Mobile));
                }
                if (!model.UserName.IsNullOrWhiteSpace())
                {
                    query = query.Where(m => m.UserName.Contains(model.UserName));
                }
            }

            return View(query.ToList());
        }

        public async Task<IActionResult> Edit(long id)
        {
            var user = await _userStorage.FindAsync(id);
            if (user == null)
            {
                return NotFound();
            }
            return View(user);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(EditUserPointsModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = await _userStorage.FindAsync(model.Id);
            if (user == null)
            {
                return NotFound();
            }

            user.IncreaseTradingPoint(model.TradingPoints);
            user.IncreaseExp(model.ExpPoints);
            var rows= _userStorage.Context.Commit();
            if (rows > 0)
            {
                return RedirectToAction("Index");
            }
            ModelState.AddModelError("error", "提交错误");
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> ResetPwd(int userId)
        {
            var user = await _userStorage.FindAsync(userId);
            if (user == null)
            {
                return NotFound();
            }

            var pwdSalt = PasswordHasher.GeneratePasswordSalt();
            var pwd = PasswordHasher.GeneratePassword("123456", pwdSalt);

            user.SetPassword(pwd, pwdSalt);
            await _userStorage.Context.CommitAsync();
            return Ok();
        }
    }
}